from django.http import HttpResponse
from django.shortcuts import render, redirect

from app01 import models


def depart_list(request):
    # 1. 获取所有部门信息
    depart_list = models.Department.objects.all()

    return render(request, 'depart_list.html', {'depart_list': depart_list})


def depart_add(request):
    # 1. 获取用户提交的数据
    if request.method == 'POST':
        depart_name = request.POST.get('title')
        # 2. 将数据写入到数据库
        models.Department.objects.create(title=depart_name)
        # 3. 跳转到部门列表页面
        return redirect('/depart/list/')

    return render(request, 'depart_add.html')


def depart_delete(request):
    # 1. 获取用户提交的数据
    depart_id = request.GET.get('nid')
    # 2. 将数据写入到数据库
    models.Department.objects.filter(id=depart_id).delete()
    # 3. 跳转到部门列表页面
    return redirect('/depart/list/')


def depart_edit(request, nid):
    if request.method == 'GET':
        # 根据nid获取当前编辑的部门信息
        row_obj = models.Department.objects.filter(id=nid).first()
        print(row_obj.id, row_obj.title)
        return render(request, 'depart_edit.html', {'row_obj': row_obj})

    title = request.POST.get('title')
    models.Department.objects.filter(id=nid).update(title=title)
    return redirect('/depart/list/')


def depart_multi(request):
    """批量上传(excel文件)"""

    # 1.获取用户上传的文件对象
    file_object = request.FILES.get('exc')

    # print(request.POST)
    # print(request.FILES)
    # print(type(file_object))

    # 直接打开excel并读取内容
    from openpyxl import load_workbook

    # 2.对象传递给openpyxl，由openpyxl读取文件的内容
    work_book_object = load_workbook(file_object)
    sheet = work_book_object.worksheets[0]

    # cell = sheet.cell(1, 1)
    # print(cell.value)

    # 3.循环获取每一行数据
    for row in sheet.iter_rows(min_row=2):
        text = row[0].value
        exists = models.Department.objects.filter(title=text).exists()
        if not exists:
            models.Department.objects.create(title=text)

    return redirect('/depart/list/')
